package com.gxd.web.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gxd.domain.Address;
import com.gxd.domain.Cart;
import com.gxd.domain.Order;
import com.gxd.domain.User;
import com.gxd.service.AddressService;
import com.gxd.service.CartService;
import com.gxd.service.OrderService;
import com.gxd.service.impl.AddressServiceImpl;
import com.gxd.service.impl.CartServiceImpl;
import com.gxd.service.impl.OrderServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@WebServlet("/orderservlet")
public class OrderServlet extends ServletBase {
    CartService cartService = new CartServiceImpl();
    OrderService orderService = new OrderServiceImpl();


    public String getAllOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {


        List<Order> orderList=orderService.findAll();
        request.setAttribute("orderList",orderList);
        return "forward:/admin/showAllOrder.jsp";
    }
    public String paySuccess(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String result = request.getParameter("result");
        Map map = JSON.parseObject(result, Map.class);
        JSONObject jsonObject = (JSONObject) map.get("result");
        String result_code = (String) jsonObject.get("result");
        if("success".equalsIgnoreCase(result_code)){
            String orderNo= (String) jsonObject.get("out_trade_no");
            Order order = new Order();
            order.setId(orderNo);
            order.setStatus("已支付");
            OrderService orderService=new OrderServiceImpl();
            orderService.paySuccess(order);
        }
        request.setAttribute("msg","支付成功");
        return "forward:/message.jsp";

    }
        public String addOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("user");
        String aid = request.getParameter("aid");
        OrderService orderService=new OrderServiceImpl();
        Order order=orderService.addOrder(user.getId(),aid);
        request.setAttribute("order",order);
        return "forward:/orderSuccess.jsp";
    }
    public String getOrderView(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("user");
        List<Cart> carts = cartService.findUid(user.getId());
        request.setAttribute("carts",carts);

        AddressService addressService = new AddressServiceImpl();
        List<Address> addList=addressService.findByUid(user.getId());
        request.setAttribute("addList",addList);
        return "forward:/order.jsp";
    }
}
